import { useModel } from "umi";
import { useReactive } from "ahooks";
import { message } from "antd";

import { AllServicers, UpdateServicerStatus, UpdateServicerIsAuth, AllOrganizationApplicationAuthorizedRecordsBySpUuid } from "../_graphql/servicer";
import { CreateOrgAndApplicaitonServicer, FindApplicationServicer, CreateApplicationServicer } from "../_graphql/servicer";
import { AllOrganizationApplicationCustomersBySpUuid, UpdateServicerRoles } from "../_graphql/servicer";
import { FindOrganization } from "../_graphql/resource";

const useServicer = () => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        dataLoading: false,
        submitLoading: false,
        servicers: [],
        totalCount: 0,
        selectedServicer: {},
        customers: [],
        authorizeRecords: [],
    });

    const loadServicers = async (spUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllServicers, variables: {} });
        if (res && res?.a?.nodes?.length > 0) {
            let servicers =
                res.a.nodes.map((item) => ({
                    isAuth: item.isAuth,
                    oasStat: item.oasStat,
                    oasCrti: item.oasCrti,
                    oasRole: item.oasRole,
                    ...item.b,
                })) || [];
            state.servicers = servicers;
            if (spUuid) {
                state.selectedServicer = state.servicers.find((item) => item.oiUuid === spUuid);
            } else {
                state.selectedServicer = state.servicers.find((item) => item.oiUuid === state.selectedServicer?.oiUuid);
                !state.selectedServicer && state.servicers.length > 0 && (state.selectedServicer = state.servicers[0]);
            }
            state.selectedServicer = servicers[0];
            state.totalCount = res?.a?.totalCount || 0;
        }
        state.dataLoading = false;
    };

    const setSelectedServicer = (data) => (state.selectedServicer = data);

    const loadServicerCustomers = async (oiUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: AllOrganizationApplicationCustomersBySpUuid,
            variables: { spUuid: oiUuid },
        });
        state.customers = res?.a?.nodes.map((item) => ({ oacStat: item.oacStat, oacCrti: item.oacCrti, ...item.b })) || [];
        state.dataLoading = false;
        return res?.a?.nodes || null;
    };

    const addServicer = async (item, callback) => {
        const saveData = {
            oiUuid: item.uuid,
            oiUscc: item.uniformSocialCreditCode,
            oiName: item.fullName,
            oiJoti: new Date().getUTCTime(),
            oiUpti: new Date().getUTCTime(),
            oiPrin: item.officeLocationJson[0]?.text || "",
            oiCity: item?.officeLocationJson[1]?.text || "",
            oiDist: item?.officeLocationJson[2]?.text || "",
            oiStre: item?.officeLocationJson?.length > 3 ? item.officeLocationJson[3]?.text : "",
            oiAddr: item.officeLocationAddress || "",
            oiJoty: "务链应用市场管理添加",
            oiType: item.type,
            oiInty: item.industryType || "",
            oiFupy: item.pinyinFullName || "",
            oiPyin: item.pinyinInitial || "",
        };

        let res = await graphqlFetchPlatform({ query: FindOrganization, variables: { oiUuid: item.uuid } });
        if (res?.a?.oiUuid) {
            res = await graphqlFetchPlatform({ query: FindApplicationServicer, variables: saveData });
            if (!res?.a?.oiUuid) {
                res = await graphqlFetchPlatform({ query: CreateApplicationServicer, variables: { oiUuid: item.uuid, oasCrti: new Date().getUTCTime() } });
            }
        } else {
            res = await graphqlFetchPlatform({ query: CreateOrgAndApplicaitonServicer, variables: { ...saveData, oasCrti: new Date().getUTCTime() } });
        }
        if (res) {
            callback && callback(res);
        }
    };

    const deleteServicer = async (oiUuid, callback) => {
        let res = await loadServicerCustomers(oiUuid);
        if (res) {
            if (res.length > 0) return message.warning("该服务商存在服务的客户信息，不能删除");

            let query = `mutation MyMutation($oiUuid: UUID!) {
                deleteOrganizationApplicationServicerByOiUuid(input: { oiUuid: $oiUuid }) {
                  clientMutationId
                }
            }`;
            let res1 = await graphqlFetchPlatform({ query, variables: { oiUuid } });
            res1 && callback && callback();
        }
    };

    const updateIsAuth = async (oiUuid, isAuth, callback) => {
        let res = await graphqlFetchPlatform({
            query: UpdateServicerIsAuth,
            variables: { oiUuid, isAuth },
        });
        res && callback && callback();
    };

    const updateStatus = async (oiUuid, oasStat, callback) => {
        let res = await graphqlFetchPlatform({
            query: UpdateServicerStatus,
            variables: { oiUuid, oasStat },
        });
        res && callback && callback();
    };

    const updateSelectedServicerRoles = async (servicer, roles) => {
        let index = state.servicers.findIndex((item) => item.oiUuid === servicer.oiUuid);
        if (index >= 0) {
            roles = Array.from(new Set(roles));
            let res = await graphqlFetchPlatform({
                query: UpdateServicerRoles,
                variables: { oiUuid: servicer.oiUuid, oasRole: roles },
            });
            if (res) {
                state.servicers.splice(index, 1, { ...servicer, oasRole: roles });
                state.selectedServicer = state.servicers.find((item) => item.oiUuid === servicer.oiUuid);
            }
        }
    };

    const loadCustomerAuthorizeRecords = async (spUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({ query: AllOrganizationApplicationAuthorizedRecordsBySpUuid, variables: { spUuid } });
        state.authorizeRecords = res?.a?.nodes.map((item) => ({ ...item, ...item.customer })) || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    return {
        ...state,
        loadServicers,
        setSelectedServicer,
        addServicer,
        deleteServicer,
        updateStatus,
        updateIsAuth,
        updateSelectedServicerRoles,
        loadServicerCustomers,
        loadCustomerAuthorizeRecords,
    };
};

export default useServicer;
